<template>
    <div class="container">
        <el-form>
            <h3 style="margin-bottom: 20px">养殖管理</h3>
<!--			<el-button-->
<!--			    size="small"-->
<!--				style="margin:20px 0"-->
<!--			    @click="addDig=true"-->
<!--			  >-->
<!--			    添加管理方式-->
<!--			  </el-button>-->
<!--			  <el-dialog title="选择" :visible.sync="addDig">-->
<!--			     <el-form ref="forms" :model="forms"  label-width="200px">-->
<!--			       <el-form-item label="管理方式名称">-->
<!--			         <el-input v-model="forms.type"></el-input>-->
<!--			       </el-form-item>-->
<!--			       <el-form-item label="是否需要投入品操作">-->
<!--			         <el-switch v-model="forms.typeLevel" :active-value='2' :inactive-value='1'></el-switch>-->
<!--			       </el-form-item>-->
<!--			       <el-form-item>-->
<!--			         <el-button type="primary" @click="addTab()">立即添加</el-button>-->
<!--			         <el-button @click="addDig=false">取消</el-button>-->
<!--			       </el-form-item>-->
<!--			     </el-form>-->
<!--			  </el-dialog>-->
            <el-tabs v-model="activeName"  @tab-click="handleClick"  style="margini-top: 20px" type="border-card"    @edit="handleTabsEdit">
                <el-tab-pane v-for="item in types" :key="item.type" :label="item.type" :name="item.type" :disabled="disabled">
                    <el-form
                        :model="ruleForm"
                        ref="ruleForm"
                        :rules="rules"
                        :label-position="labelPosition"
                        label-width="120px"
                        class="demo-ruleForm"
                    >
					<el-row v-if="item.typeLevel=='2'">
                        <el-form-item label="肥料类型：">
                            <el-select v-model='fertilizerType'>
                                <el-option
                                    v-for="item in inputs"
                                    :key="item"
                                    :label="item"
                                    :value="item"
                                ></el-option>
                            </el-select>
                        </el-form-item>
					    <el-table
					        :data="ruleForm.list"
					        bordero
					        ref="multipleTable"
					        header-cell-class-name="table-header"
					    >
					        <el-table-column prop="breedName" sortable label="品名"></el-table-column>
					        <el-table-column sortable label="规格">
					            <template slot-scope="scope">{{ scope.row.spec }}{{ scope.row.specUnits }}</template>
					        </el-table-column>
					        <el-table-column sortable label="数量">
					            <template slot-scope="scope">
					                <el-input
					                    v-model="scope.row.useNumber"
					                    @change="compare(scope.$index, scope.row)"
					                    style="width: 200px"
					                ></el-input>
					                <span style="margin-left: 10px">{{ scope.row.units }}</span>
					            </template>
					        </el-table-column>
					        <el-table-column prop="supply" sortable label="供应商"></el-table-column>
					        <el-table-column prop="buyTime" sortable label="购买时间"></el-table-column>
					    </el-table>
					    <div @click="addManure" class="addManure">添加肥料</div>
					   </el-row>
                        <el-row>
                            <el-col :span="10">
                                <el-form-item :label="item.type+'方式：'" prop="way" v-if="item.typeLevel==1">
                                    <el-select v-model="ruleForm.way" placeholder="请选择" style="width: 300px">
                                        <div v-if='activeName !== "种子种苗处理"'>
                                            <el-option label="机械" value="机械"></el-option>
                                            <el-option label="人工" value="人工"></el-option>
                                        </div>
                                        <div v-else>
                                            <el-option label='消毒' value='消毒'></el-option>
                                            <el-option label='晾晒' value='晾晒'></el-option>
                                            <el-option label='浸种' value='浸种'></el-option>
                                            <el-option label='净选' value='净选'></el-option>
                                            <el-option label='拌种' value='拌种'></el-option>
                                            <el-option label='种子包衣' value='种子包衣'></el-option>
                                            <el-option label='催芽处理' value='催芽处理'></el-option>
                                            <el-option label='药种磁场处理' value='药种磁场处理'></el-option>
                                        </div>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="开始时间：" prop="beginTime">
                                    <el-date-picker
                                        v-model="ruleForm.beginTime"
                                        type="date"
                                        @change="gettime"
                                        value-format="yyyy-MM-dd"
                                        placeholder
                                        style="width: 300px"
                                    ></el-date-picker>
                                </el-form-item>
                                <el-form-item label="操作图片：">
                                    <el-upload
                                        class="upload-poster"
                                        action="https://jsonplaceholder.typicode.com/posts/"
                                        :show-file-list="false"
                                        :on-change="imgPreview"
                                        :auto-upload="false"
                                    >
                                        <img v-if="headImg" :src="headImg" class="avatar" />
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    jpg、png、gif格式，不超过20MB
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="负责人：" prop="principalName">
                                    <el-select
                                        v-model="ruleForm.principalName"
                                        style="width: 300px"
                                        value-key="id"
                                        @change="getuser"
                                        placeholder=""
                                    >
                                        <el-option v-for="item in userAll" :key="item.id" :label="item.name" :value="item">{{item.name }}</el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="结束时间：" prop="endTime">
                                    <el-date-picker
                                        v-model="ruleForm.endTime"
                                        type="date"
                                        @change="gettime"
                                        value-format="yyyy-MM-dd"
                                        style="width: 300px"
                                    ></el-date-picker>
                                </el-form-item>
                                <el-form-item label="执行标准：">
                                    <el-upload
                                        class="upload-poster"
                                        action="https://jsonplaceholder.typicode.com/posts/"
                                        :show-file-list="false"
                                        :on-change="imgPreviewExcute"
                                        :auto-upload="false"
                                    >
                                        <img v-if="excuteImg" :src="excuteImg" class="avatar" />
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    jpg、png、gif格式，不超过20MB
                                </el-form-item>
                            </el-col>
                            <el-col :span='12'>
                                <el-form-item label='备注:'>
                                    <el-input type='textarea' v-model="ruleForm.remark" rows='4'></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                                <!--  产品说暂时不要了  2024.6.3 sameki  -->
<!--                        <el-row style="margin-top:10px;">-->
<!--                            <h3 style='margin: 20px 0'>用工记录</h3>-->
<!--                            <el-col>-->
<!--                                <h4 v-if='hasFile'>{{ruleForm.file.name}}</h4>-->
<!--                            </el-col>-->
<!--                            <el-row>-->
<!--                                <el-col style='padding: 10px 0'>-->
<!--                                    <el-upload-->
<!--                                        class="upload-import"-->
<!--                                        style='float: left;background-color: initial'-->
<!--                                        ref="upload"-->
<!--                                        action=""-->
<!--                                        :on-change="importExcel"-->
<!--                                        accept=".xlsx,.xls"-->
<!--                                        :show-file-list='false'-->
<!--                                        :auto-upload="false">-->
<!--                                        <el-button class='theme-button' slot="trigger" size="small">导入模板</el-button>-->
<!--                                    </el-upload>-->
<!--                                    <el-button class='theme-button' @click='downloadTemplate'>下载导入模板</el-button>-->
<!--                                </el-col>-->
<!--                            </el-row>-->
<!--                        </el-row>-->

                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <el-form>
                <el-form-item class="footerFixed">
                    <div class='fixed'>
                        <el-button class='theme-button' @click="submitrule('ruleForm')">提交</el-button>
                        <el-button @click="backPage">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <el-dialog title="选择" :visible.sync="dialogTableVisible">
                <el-table :data="tableData" border style="margin-top: 20px" ref="multipleTable" header-cell-class-name="table-header">
                    <el-table-column prop="inputsName" sortable label="品名"></el-table-column>
                    <el-table-column sortable label="规格">
                        <template slot-scope="scope">{{ scope.row.spec }}{{ scope.row.specUnits }}</template>
                    </el-table-column>
                    <el-table-column sortable label="数量">
                        <template slot-scope="scope">{{ scope.row.surplusNumber }}{{ scope.row.units }}</template>
                    </el-table-column>
                    <el-table-column prop="supplyName" sortable label="供应商"></el-table-column>
                    <el-table-column prop="buyTime" sortable label="购买时间"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleSelect(scope.$index, scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>
        </el-form>
    </div>
</template>

<script>
import { farm_save,getAllType, user_findByAll, inputs_findByList,farm_finish,farm_findById,addType,delType } from '@/request/api';
import { soil_findByBaseId } from '@/request/breedApi'
import uploadImg from '@/components/common/uploadImg.vue';
import axios from 'axios';
export default {
    components:{
        uploadImg
    },
    data() {
        return {
            inputs:['底肥','追肥','叶面肥','水肥','人工施肥'],

			disabled:false,
            plotlist: [],
            soilId: '',
            userAll: '',
            tableData: [],
            dialogTableVisible: false,
            headImg: '',
            excuteImg:'',
            value: '',
			addDig:false,
			forms: {
			          type: '',
			          typeLevel: 1,
			        },
			types:[],
            activeName:"",
            labelPosition: 'right',
            fertilizerType:'',
            ruleForm: {
                standardImgFile:'',//执行标准
                standardImg:'',//执行标准图片名
                plantId: '',
                type: '',
                way: '',
                beginTime: '',
                endTime: '',
                list: [],
                status: 0,
                principalId: '',
                principalName: '',
                soilId: '',
                soilName: ''
            },
            nyshow: false,
            id: '',
            rules: {
                way: [{ required: true, message: '不能为空', trigger: 'change' }],
                beginTime: [{ required: true, message: '不能为空', trigger: 'change' }],
                principalName: [{ required: true, message: '不能为空', trigger: 'change' }],
                endTime: [{ required: true, message: '不能为空', trigger: 'change' }],
                soilName: [{ required: true, message: '不能为空', trigger: 'change' }],
				type:[{required: true, message: '不能为空', trigger: 'change'}],
                },
            currentPage: 1,
            query: '',
            hasFile:false,
            curTabIndex:0,
            jyId:''
        };
    },
    mounted() {
		console.log(this.$route.query)
        this.ruleForm.batch = this.$route.query.batch
        this.ruleForm.plantId = this.$route.query.id;
		this.sid = this.$route.query.sid
        this.jyId = this.$route.query.jyId
		if(this.sid != undefined){
			this.disabled = true
			this.getdetails()
		}
        this.init();
		this.getinputs()
    },
    watch:{
        'ruleForm.file'(val){
            if(val){
                this.hasFile = true
            }else{
                this.hasFile = false
            }
        }
    },
    methods: {
        //下载xlsx文件
        downloadFile(url,fileName){
            //由于之前的前端没有封装导入模板接口，所以只能用axios
            axios.get(localStorage.getItem('requestUrl')+url,{responseType:'arraybuffer'}).then(res=>{
                const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download',`${fileName}.xlsx`)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(url)
                this.$notify({
                    title: '操作成功',
                    message: '下载成功',
                    type: 'success'
                })
            })
        },
        //下载导入模板
        async downloadTemplate() {
            //type (1=农事用工, 2=种植用工, 3=加工用工, 4=采收用工)
            this.downloadFile('labor/exportLaborTemplate?type=1','农事导入模板')
        },
        importExcel(file){
            this.ruleForm.file = file.raw
            this.$notify({
                title: '操作成功',
                message: '导入成功',
                type: 'success'
            })
            this.hasFile = true
        },
		getdetails(){
			farm_findById(this.sid).then((res)=>{
				this.ruleForm = res.data
			})
		},
        gettime() {
                if (this.ruleForm.beginTime != '' && this.ruleForm.endTime != '') {
                var oDate1 = new Date(this.ruleForm.beginTime);
                var oDate2 = new Date(this.ruleForm.endTime);
                if (oDate1 > oDate2) {
                    this.$notify({
                        title: '提示',
                        message: '开始时间不得早于结束时间',
                        type: 'info'
                    });
                    this.ruleForm.beginTime = '';
                    this.ruleForm.endTime = '';
                }
            }
        },
        getdk(ele) {
            this.ruleForm.soilId = ele.id;
            this.ruleForm.soilName = ele.name;
        },
        compare(index, row) {
            if (Number(row.useNumber) > Number(row.number)) {
                this.$notify({
                    title: '提示',
                    message: '使用数量不能大于总量',
                    type: 'info',
                    duration: 1000
                });
                row.useNumber = '';
            }
        },
        getuser(ele) {
            this.ruleForm.principalId = ele.id;
            this.ruleForm.principalName = ele.name;
        },
        getinputs() {
            var params = {
                type: this.query,
                page: this.currentPage
            };
            inputs_findByList(params).then((res) => {
                this.tableData = res.rows;
            });
        },
        init() {
			// 获取方式
			this.getAllType()
            // 获取员工
            user_findByAll('').then((res) => {
                this.userAll = res.data;
            });
            //获取地块
            // console.log(this.ruleForm.plantId,'222')
            soil_findByBaseId(`${this.ruleForm.plantId}/2`).then((res) => {
                this.plotlist = res;
            });
            // plot_findByAll({ type: 2 }).then((res) => {
            //     this.plotlist = res.data;
            // });
        },
		getAllType(){
			getAllType('?state=1&jyId='+this.jyId).then((res)=>{
				console.log(res)
				if(res.code=='200'){
					this.types = res.data
					this.activeName = res.data[0].type
				}
			})
		},
        handleClick(e) {
            this.curTabIndex = e.index
			// console.log(e.index)
			// this.activeName=this.types[e.index]
            // if (this.activeName == '施肥') {
            //     this.query == '肥料';
            //     this.getinputs();
            // }
            // if (this.activeName == '除草' || this.activeName == '病虫害') {
            //     this.query = '农药';
            //     this.getinputs();
            // } else {
            //     this.nyshow = false;
            // }
			// this.ruleForm.typeLevel =
            this.ruleForm.type = this.activeName;
            this.ruleForm.way = '';
            this.ruleForm.beginTime = '';
            this.ruleForm.endTime = '';
            this.headImg = '';
            this.excuteImg = '';
            this.ruleForm.standardImgFile = ''
            this.ruleForm.standardImg = ''
            this.ruleForm.file = '';
            this.ruleForm.img = '';
            this.ruleForm.files = '';
            this.ruleForm.principalName = '';
            this.ruleForm.principalId = '';
            this.ruleForm.list = [];
            this.ruleForm.soilId = '';
            this.ruleForm.soilName = '';
            console.log( this.ruleForm.type,'$$$');
        },
		// addTab(formName){
        //
		// 	this.$refs['forms'].validate(async(valid) => {
		// 		 if (!valid)return
		// 		 console.log(this.forms)
		// 		let res = await addType(this.forms)
		// 		console.log(res)
		// 		if(res.code=='200')this.$message.success("添加成功")
		// 		this.getAllType()
		// 		this.addDig=false
		// 	})
		// },
		handleTabsEdit(targetName, action){
			if(action=='add'){
				this.addDig=true
			}else{
				this.$confirm('确定删除该管理方式?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(async () => {
				    let delId =[]
					let tabs = this.types;
					let activeNames = this.activeName;
					tabs.forEach((tab,index)=>{
							if(tab.type==targetName){
								delId.push(tab.id)
								let nextTab = tabs[index + 1] || tabs[index - 1];
								   if (nextTab) {
								     activeNames = nextTab.type;
								  }
							}
					})
					this.activeName = activeNames;
					this.types = tabs.filter(tab => tab.type !== targetName);
					console.log(delId)
					let res= await delType(delId)
					if(res.code!='200')return
				      this.$message({
				        type: 'success',
				        message: '删除成功!'
				      });
				    }).catch(() => {
				      this.$message({
				        type: 'info',
				        message: '已取消删除'
				      });
				    });
			}
			console.log(targetName, action)
		},
        submitrule(formName) {
            this.$nextTick(()=>{
                this.$refs.ruleForm[this.curTabIndex].validate(async(valid) => {
                    if(valid){
                        let formdata = new FormData();
                        this.ruleForm.farmInputsList = JSON.stringify(this.ruleForm.list);
                        this.ruleForm.type = this.activeName
                        for (var a in this.ruleForm) {
                            if (this.ruleForm[a] == null || this.ruleForm[a] == 'null') {
                                this.ruleForm[a] = '';
                                formdata.append(a, '');
                            } else {
                                formdata.append(a, this.ruleForm[a]);
                            }
                        }
                        for (const formdataKey of formdata) {
                            console.log(formdataKey, formdata[formdataKey]);
                        }
                        if(this.sid != undefined){
                            farm_finish(formdata).then((res)=>{
                                this.$notify({
                                    title: '提示',
                                    message: '任务完成',
                                    type: 'success'
                                });
                                this.$router.go(-1);
                            })
                        }else{
                            farm_save(formdata).then((res) => {
                                this.$notify({
                                    title: '操作成功',
                                    message: '保存成功',
                                    type: 'success'
                                });
                                this.$router.go(-1);
                            });
                        }
                    }
                })

            })
        },

        backPage() {
            this.$router.go(-1);
        },
        imgPreviewExcute(file, fileList) {
            this.excuteImg = URL.createObjectURL(file.raw);
            let fileName = file.name;
            let regex = /(.jpg|.gif|.png|.jpeg)$/;
            if (regex.test(fileName.toLowerCase())) {
                this.ruleForm.standardImgFile = file.raw;
                this.ruleForm.standardImg = file.name;
            } else {
                this.$message.error('请选择图片文件');
            }
        },
        imgPreview(file, fileList) {
            this.headImg = URL.createObjectURL(file.raw);
            let fileName = file.name;
            let regex = /(.jpg|.gif|.png|.jpeg)$/;
            if (regex.test(fileName.toLowerCase())) {
                this.ruleForm.files = file.raw;
                this.ruleForm.img = file.name;
            } else {
                this.$message.error('请选择图片文件');
            }
        },
        addManure() {
            this.dialogTableVisible = true;
        },
        handleSelect(index, row) {
            console.log(this);
            this.ruleForm.list.push({
                breedName: row.inputsName,
                spec: row.spec,
                specUnits: row.specUnits,
                inputsId: row.id,
                useNumber: row.surplusNumber,
                units: row.units,
                supply: row.supplyName,
                buyTime: row.buyTime,
                type: this.activeName,
                number: row.surplusNumber,
                fertilizerType:this.fertilizerType,
                no: row.no,
                time:this.$util.dateFormat('yyyy-MM-dd',new Date()),
                muUserNum:row.surplusNumber
            });
            this.dialogTableVisible = false;
        }
    }
};
</script>

<style lang='less' scoped>
@import "@/assets/css/common.less";
/deep/.el-tabs__new-tab{
    margin: 12px 15px 9px 10px;
}
/deep/.el-tabs__item.is-active {
    color: #1BC46D !important;
}

/deep/.el-tabs__active-bar {
    background-color: #1BC46D !important;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 180px;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.addManure {
    border-radius: 8px;
    margin-bottom: 20px;
    width: 100%;
    height: 60px;
    line-height: 60px;
    text-align: center;
    font-size: 16px;
    background: #EBF5FF 100%;
}
</style>
